package com.example.demo.fork_join;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * ClassName: ForkJoinDemo
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/08/01-13:35:00
 * Description:
 */
class TaskExample extends RecursiveTask<Long> {
    private int start;
    private int end;
    private long sum;
    private int middle;

    public TaskExample(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        System.out.println("任务" + start + "=====" + end + "累加开始");
        /**
         * 两数相差10以内, 直接累加计算结果
         * 比如1+2+3+4+ ~ + 10；
         */
        if (end - start <= 10) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            /**
             * 采用二分法
             */
            middle = (end + start) / 2;
            /**
             * 递归调用, 切分为2个小任务
             */
            TaskExample taskExample1 = new TaskExample(start, middle);
            TaskExample taskExample2 = new TaskExample(middle + 1, end);
            taskExample1.fork();
            taskExample2.fork();
            sum = taskExample1.join() + taskExample2.join();
        }
        return sum;
    }
}

public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TaskExample taskExample = new TaskExample(1, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinTask = forkJoinPool.submit(taskExample);
        System.out.println(forkJoinTask.isCompletedAbnormally());
        System.out.println(forkJoinTask.get());
        forkJoinPool.shutdown();
    }
}
